package com.hbfec.fileserver.aspect;

import com.hbfec.fileserver.constant.CacheKeys;
import com.hbfec.fileserver.service.CacheService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 定时任务切面
 */
@Aspect
@Component
public class TaskAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(TaskAspect.class);

    @Value("${fileserver.persist.lock-timeout}")
    private Integer lockTimeout;

    @Autowired
    private CacheService cache;

    /**
     * 定时任务 Pointcut
     */
    @Pointcut("execution(public void com.hbfec.fileserver.task.FileBatchUpdateTask.run())")
    public void file() {
    }

    /**
     * 定时任务切面
     *
     * @param pjp ProceedingJoinPoint
     */
    @Around("file()")
    public void fileAround(ProceedingJoinPoint pjp) {
        String lock = null;
        try {
            // 获取锁
            lock = cache.getLock(CacheKeys.FILE_QUEUE_LOCK, lockTimeout);
            if (lock != null) {
                pjp.proceed();
            }
        } catch (Throwable throwable) {
            LOGGER.error("从缓存中获取锁或释放锁时出现异常", throwable);
        } finally {
            if (lock != null) {
                // 释放锁
                if (!cache.releaseLock(CacheKeys.FILE_QUEUE_LOCK, lock)) {
                    LOGGER.error("释放锁失败");
                }
            }
        }
    }
}
